import React, { useReducer } from 'react';

interface IStateType {
  current: number;
  uploadInfo: Record<string, any> | null;
  dataList: Record<string, any>[];
  uploadLoading: boolean;
  total: number | null;
}

interface IActionType {
  type:
    | 'changeCurrent'
    | 'setUploadInfo'
    | 'updateDataList'
    | 'uploadLoading'
    | 'setTotal';
  payload: Record<string, any>;
}

export const useUploadModal = () => {
  const reducer = (state: IStateType, action: IActionType) => {
    switch (action.type) {
      case 'changeCurrent':
        return {
          ...state,
          current: action.payload?.current,
        };
      case 'setUploadInfo':
        return {
          ...state,
          uploadInfo: action.payload?.uploadInfo,
        };
      case 'updateDataList':
        return {
          ...state,
          dataList: action.payload?.dataList,
        };
      case 'uploadLoading':
        return {
          ...state,
          uploadLoading: action.payload?.uploadLoading,
        };
      case 'setTotal':
        return {
          ...state,
          total: action.payload?.total,
        };
      default:
        throw new Error();
    }
  };

  const initialState = {
    current: 0,
    uploadInfo: null,
    dataList: [],
    uploadLoading: false,
    total: null,
  };

  const [state, dispatch] = useReducer(reducer, initialState);

  return {
    state,
    dispatch,
  };
};

interface IDraft extends IStateType {
  dispatch: React.Dispatch<IActionType>;
}

const draft: IDraft = {
  current: 0,
  uploadInfo: null,
  total: null,
  dataList: [],
  uploadLoading: false,
  dispatch: () => {},
};

export const UploadContext = React.createContext(draft);
